// pages/profile/index.ts
const pageStack = getCurrentPages()
// console.log(pageStack[0])
Page({
  /**
   * 页面的初始数据
   */
  data: {
    avatarinfo: '',
    nickName: '',
    avatar: '',
  },
  onLoad() {
    const app = getApp()
    console.log(app.UserProfile)
    this.setData({
      nickName: app.UserProfile.nickName,
      avatar: app.UserProfile.avatar,
    })
  },
  getUserNickname(ev) {
    // 更新用户昵称
    this.updateNickname(ev.detail.value)
  },
  async updateNickname(nickName) {
    // 调用更新昵称接口
    await wx.http
      .put('/userInfo', {
        nickName,
      })
      .then((res) => {
        if (res.code !== 10000) return wx.utils.messagePrompt('更新昵称失败！')
        // 借助页面栈实例跟新数据
        console.log(pageStack[0])
        pageStack[0].setData({ nickName })
        const app = getApp()
        app.UserProfile.nickName = nickName
      })
  },
  // 获取用户头像
  getUserAvatars(ev) {
    console.log(ev)
    // 更新用户头像
    this.updateAvatar(ev.detail.avatarUrl)
  },
  updateAvatar(Avatar) {
    wx.uploadFile({
      filePath: Avatar,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: 'Bearer ' + getApp().token,
      },
      formData: {
        type: 'avatar',
      },
      success: (res) => {
        console.log(res)
        const data = JSON.parse(res.data)
        if (data.code !== 10000) return wx.utils.messagePrompt('更新头像失败！')
        pageStack[0].setData({ avatar: data.data.url })
        this.setData({ avatar: data.data.url })
        const app = getApp()
        app.UserProfile.avatar = data.data.url
      },
    })
  },
})
